/**
 * @file CartPage.jsx
 * @description 购物车页面组件。
 */
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';
import { addItem, removeItem } from '../store/cartSlice';
import { FaPlus, FaMinus, FaArrowLeft, FaLongArrowAltRight, FaTrashAlt } from 'react-icons/fa'; // 导入图标

const CartPage = () => {
  const cartItems = useSelector((state) => state.cart.items);
  const dispatch = useDispatch();

  const handleIncreaseQuantity = (item) => {
    dispatch(addItem(item));
  };

  const handleDecreaseQuantity = (item) => {
    dispatch(removeItem(item));
  };

  // 可选：添加一个一次性移除整个商品条目的函数
  const handleRemoveItemCompletely = (item) => {
    // 为了完全移除，我们需要一个能设置数量为0或直接移除的action，或者多次调用removeItem
    // 简单起见，我们假设多次调用removeItem直到移除
    // 或者在cartSlice中添加一个更直接的移除action
    let currentItem = cartItems.find(i => i.id === item.id);
    if (currentItem) {
        for (let i = 0; i < currentItem.qty; i++) {
            dispatch(removeItem(item));
        }
    }
  };


  const EmptyCart = () => (
    <div className="container py-5">
      <div className="row">
        <div className="col-md-12 py-5 bg-light text-center">
          <h4 className="p-3 display-5">你的购物车是空的</h4>
          <Link to="/products" className="btn btn-outline-dark mx-4">
            <FaArrowLeft className="me-2" />
            继续购物
          </Link>
        </div>
      </div>
    </div>
  );

  const ShowCart = () => {
    let subtotal = 0;
    let totalItems = 0;
    cartItems.forEach(item => {
      subtotal += item.price * item.qty;
      totalItems += item.qty;
    });
    const shipping = totalItems > 0 ? 30.00 : 0;
    const totalAmount = subtotal + shipping;

    return (
      <section className="h-100" style={{ backgroundColor: '#eee' }}>
        <div className="container py-5 h-100">
          <div className="row d-flex justify-content-center align-items-center h-100">
            <div className="col-10">
              <div className="d-flex justify-content-between align-items-center mb-4">
                <h3 className="fw-normal mb-0 text-black">我的购物车</h3>
              </div>

              {cartItems.map((item) => (
                <div className="card rounded-3 mb-4" key={item.id}>
                  <div className="card-body p-4">
                    <div className="row d-flex justify-content-between align-items-center">
                      <div className="col-md-2 col-lg-2 col-xl-2">
                        <img
                          src={item.image}
                          className="img-fluid rounded-3"
                          alt={item.title}
                          style={{ maxHeight: '100px', objectFit: 'contain' }}
                        />
                      </div>
                      <div className="col-md-3 col-lg-3 col-xl-3">
                        <p className="lead fw-normal mb-2">{item.title.substring(0, 30)}...</p>
                        <p className="small">
                          <span className="text-muted">分类: </span>{item.category}
                        </p>
                      </div>
                      <div className="col-md-3 col-lg-3 col-xl-2 d-flex align-items-center">
                        <button
                          className="btn btn-link px-2"
                          onClick={() => handleDecreaseQuantity(item)}
                          aria-label="减少数量"
                        >
                          <FaMinus />
                        </button>
                        <input
                          id={`form${item.id}`}
                          min="0"
                          name="quantity"
                          value={item.qty}
                          type="number"
                          className="form-control form-control-sm text-center"
                          readOnly
                          style={{width: '50px'}}
                        />
                        <button
                          className="btn btn-link px-2"
                          onClick={() => handleIncreaseQuantity(item)}
                          aria-label="增加数量"
                        >
                          <FaPlus />
                        </button>
                      </div>
                      <div className="col-md-2 col-lg-2 col-xl-2 offset-lg-1">
                        <h5 className="mb-0">${(item.price * item.qty).toFixed(2)}</h5>
                      </div>
                      <div className="col-md-1 col-lg-1 col-xl-1 text-end">
                        <button 
                            className="btn btn-link text-danger" 
                            onClick={() => handleRemoveItemCompletely(item)}
                            aria-label="移除商品"
                        >
                          <FaTrashAlt />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}

              <div className="card">
                <div className="card-body">
                  <div className="d-flex justify-content-between mb-2">
                    <p className="mb-2">小计 ({totalItems} 件)</p>
                    <p className="mb-2">${subtotal.toFixed(2)}</p>
                  </div>
                  <div className="d-flex justify-content-between mb-2">
                    <p className="mb-2">运费</p>
                    <p className="mb-2">${shipping.toFixed(2)}</p>
                  </div>
                  <hr />
                  <div className="d-flex justify-content-between mb-4">
                    <p className="mb-2">总金额</p>
                    <p className="mb-2 fw-bold">${totalAmount.toFixed(2)}</p>
                  </div>
                  <Link to="/checkout" className={`btn btn-info btn-block btn-lg ${totalItems === 0 ? 'disabled' : ''}`}>
                    <div className="d-flex justify-content-between">
                      <span>前往结算 <FaLongArrowAltRight className="ms-2" /></span>
                    </div>
                  </Link>
                </div>
              </div>

            </div>
          </div>
        </div>
      </section>
    );
  };

  return (
    <div className="container my-3 py-3">
      {cartItems.length > 0 ? <ShowCart /> : <EmptyCart />}
    </div>
  );
};

export default CartPage;